package com.example.coffeejava.Config;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.example.coffeejava.Dto.UserDto;
import com.example.coffeejava.Entity.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.example.coffeejava.utils.Constants.LOGIN_USER_KEY;
import static com.example.coffeejava.utils.Constants.LOGIN_USER_TTL;

public class RefreshTokenInterceptor implements HandlerInterceptor {
    private StringRedisTemplate stringRedisTemplate;
    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate){
        this.stringRedisTemplate=stringRedisTemplate;
    }
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,Object handler){

        //通过token从缓存中获取个人信息，存入线程池，设置redis过期时间
        //获取token
        String token=httpServletRequest.getHeader("authorization");
        if(StrUtil.isBlank(token)){
            return true;
        }
        String key=LOGIN_USER_KEY+token;
        //获取缓存里面usermap
        Map<Object,Object> usermap=stringRedisTemplate.opsForHash().entries(key);
        if(usermap.isEmpty()){
            return true;
        }
      //存入线程池
        UserDto userDto= BeanUtil.fillBeanWithMap(usermap,new UserDto(),false);
        System.out.println(userDto+"12345");
        UserHolder.saveUser(userDto);
        stringRedisTemplate.expire(key,LOGIN_USER_TTL, TimeUnit.MINUTES);
        if(userDto==null){
            httpServletResponse.setStatus(401);
            return false;
        }
        return true;



    }
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,Object handler,Exception ex){
        UserHolder.removeUser();

    }
}
